from simpledcpp.core.base import DCPPTCPSocket, start_new_thread, DCPPEvent, DCPPPart
import sys, random, os

class PrepareMe(DCPPPart):
	def __init__(self, parent, addr):
		DCPPPart.__init__(self, parent)
		self._socket = DCPPTCPSocket()
		self._addr = addr
                self._lock = 'EXTENDEDPROTOCOLABCABCABCABCABCABC'
                filed = open(os.path.join(os.getenv("HOME"), ".simpledcpp/ext.key"))
                self._key = filed.readlines()[0]
                filed.close()
		self._thread = start_new_thread(self._prepare)

	def _prepare(self):
		self._socket.Connect(self._addr, TIMEOUT = 20)
		self.check()
		self._socket.Send('$MyNick %s|$Lock %s|'%(self.settings.get("nickname"), self._lock))
		self.check()
		data = self._socket.Recieve(TIMEOUT = 20)
		self.check()
		_n, _l, _d, _dn, _k = self._parseInfo(data)
		if _d == "Upload":
			direction = "Download"
		elif _d == "Download":
			direction = "Upload"
		else:
			self.stop()
			return

		mynumber = int(random.random() * 1000000)
		string = "$Supports ADCGet ADCSnd XmlBZList TTHF|$Direction %s %s|$Key %s|"%(direction, mynumber, self._key)
		self._socket.Send(string)
		self.check()
		if direction == "Upload":
			data = self._socket.Recieve(TIMEOUT = 20)
			self.check()
			try:
				data = data.split('|')[0].split(' ')
			except:
				self.stop()
				return
			if data[0] == '$ADCGET':
				type = data[1]
				name = data[2]
				fm = data[3]
				to = data[4]
#				print "Starting upload with parametres: %s "%_n, data
				self.Event(DCPPEvent("ON_NEED_UPLOAD",(self._socket, type,name,fm,to,_n)))
		elif direction == "Download":
#			print "Starting download"
			return

	def _parseInfo(self, data):
		try:
			commands = data.split('|')
		except:
			return (None, None, None, None, None)
		nickname = None
		lock = None
		direction = None
		direction_number = None
		key = None
		for i in commands:
			if i!="":
				values = i.split(' ')
				if values[0] == "$MyNick":
					nickname = values[1]
				elif values[0] == '$Lock':
					lock = values[1]
				elif values[0] == '$Direction':
					direction = values[1]
					direction_number = values[2]
				elif values[0] == '$Key':
					key = i.split(' ',1)[1]
		return (nickname, lock, direction, direction_number, key)			
	def stop(self):
		try:
			self._thread.kill()
		except:
			pass
		self._socket.Close()

	def check(self):
		if not self._socket.ok():
			self.stop()


class PrepareYou(DCPPPart):
	def __init__(self, parent, socket, addr):
		DCPPPart.__init__(self, parent)
		self._addr = addr
		self._socket = DCPPTCPSocket(DEBUG = False, FROM_SOCKET = socket)
                self._lock = 'EXTENDEDPROTOCOLABCABCABCABCABCABC'
                filed = open(os.path.join(os.getenv("HOME"), ".simpledcpp/ext.key"))
                self._key = filed.readlines()[0]
                filed.close()
		self._thread = start_new_thread(self._prepare)

	def _prepare(self):
		data = self._socket.Recieve()
		if data.split(':')[0] == 'magnet':
			# user send magnet to us.
			if self._addr[0] == '127.0.0.1':
				self.Event(DCPPEvent('OPEN_MAGNET', (data,)))
				self.stop()
				return
		_n, _l, notused, notused, notused = self._parseInfo(data)
		if _n == None:
			self.stop()
			return
		mynumber = int(random.random() * 1000000)
		str = "$MyNick %s|$Lock %s pk=1024|$Supports ADCGet ADCSnd XmlBZList TTHF GetZBlock ZLIG|$Direction Download %s|$Key %s|"%(self.settings.get('nickname'),self._lock,mynumber, self._key)
		self._socket.Send(str)
		data = self._socket.Recieve()
		notused, notused, _d, _dn, _k = self._parseInfo(data)
		if _d == "Download" and _dn > mynumber and False:
#			print _dn, mynumber
                        data = self._socket.Recieve(TIMEOUT = 20)
                        self.check()
			try:
                        	data = data.split('|')[0].split(' ')
			except:
				print data
                        if data[0] == '$ADCGET':
                                type = data[1]
                                name = data[2]
                                fm = data[3]
                                to = data[4]
#                               print "Starting upload with parametres: %s "%_n, data
				self.Event(DCPPEvent("ON_NEED_UPLOAD",(self._socket, type,name,fm,to,_n)))
		elif _d == "Upload" or _d == "Download": 
			self.Event(DCPPEvent("ON_NEED_DOWNLOAD",(self._socket, _n)))
		else:
			self.stop()	

        def _parseInfo(self, data):
		try:
                	commands = data.split('|')
		except:
			return (None, None, None, None, None)
                nickname = None
                lock = None
                direction = None
                direction_number = None
                key = None
                for i in commands:
                        if i!="":
                                values = i.split(' ')
                                if values[0] == "$MyNick":
                                        nickname = values[1]
                                elif values[0] == '$Lock':
                                        lock = values[1]
                                elif values[0] == '$Direction':
                                        direction = values[1]
                                        direction_number = values[2]
                                elif values[0] == '$Key':
                                        key = i.split(' ',1)[1]
                return (nickname, lock, direction, direction_number, key)

	def stop(self):
		try:
			self._thread.kill()
		except:
			pass
		self._socket.Close()

        def check(self):
                if not self._socket.ok():
                        self.stop()

